<template>
  <div class="review-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><DocumentChecked /></el-icon>
            <span class="header-title">领养申请审核</span>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索申请人姓名、电话、地址"
          clearable
          style="max-width: 300px;"
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="filterStatus"
          placeholder="选择状态"
          clearable
          style="width: 150px;"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="待审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已驳回" :value="2" />
        </el-select>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="filteredList" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="申请ID" width="80" align="center" />
        <el-table-column prop="applicantName" label="申请人" width="120" align="center" />
        <el-table-column prop="phone" label="联系电话" width="130" align="center" />
        <el-table-column prop="address" label="居住地址" min-width="180">
          <template #default="{ row }">
            <span 
              v-if="row.address && row.address.length > 15"
              class="clickable-text"
              @click="showDetailDialog('居住地址', row.address)"
            >
              {{ row.address.substring(0, 15) }}...
              <el-icon class="view-icon"><View /></el-icon>
            </span>
            <span 
              v-else-if="row.address" 
              class="clickable-text"
              @click="showDetailDialog('居住地址', row.address)"
            >
              {{ row.address }}
            </span>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="housingType" label="住房情况" width="120" align="center">
          <template #default="{ row }">
            <el-tag 
              v-if="row.housingType" 
              type="info" 
              size="small" 
              class="clickable-tag" 
              @click="showDetailDialog('住房情况', row.housingType)"
            >
              {{ row.housingType }}
              <el-icon class="view-icon"><View /></el-icon>
            </el-tag>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="familyMembers" label="家庭成员" width="120" align="center">
          <template #default="{ row }">
            <span 
              v-if="row.familyMembers && row.familyMembers.length > 10"
              class="clickable-text"
              @click="showDetailDialog('家庭成员', row.familyMembers)"
            >
              {{ row.familyMembers.substring(0, 10) }}...
              <el-icon class="view-icon"><View /></el-icon>
            </span>
            <span 
              v-else-if="row.familyMembers" 
              class="clickable-text"
              @click="showDetailDialog('家庭成员', row.familyMembers)"
            >
              {{ row.familyMembers }}
            </span>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="reason" label="领养理由" min-width="200">
          <template #default="{ row }">
            <span 
              v-if="row.reason && row.reason.length > 20"
              class="clickable-text"
              @click="showDetailDialog('领养理由', row.reason)"
            >
              {{ row.reason.substring(0, 20) }}...
              <el-icon class="view-icon"><View /></el-icon>
            </span>
            <span 
              v-else-if="row.reason" 
              class="clickable-text"
              @click="showDetailDialog('领养理由', row.reason)"
            >
              {{ row.reason }}
            </span>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="experience" label="养宠经验" min-width="200">
          <template #default="{ row }">
            <span 
              v-if="row.experience && row.experience.length > 20"
              class="clickable-text"
              @click="showDetailDialog('养宠经验', row.experience)"
            >
              {{ row.experience.substring(0, 20) }}...
              <el-icon class="view-icon"><View /></el-icon>
            </span>
            <span 
              v-else-if="row.experience" 
              class="clickable-text"
              @click="showDetailDialog('养宠经验', row.experience)"
            >
              {{ row.experience }}
            </span>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="applyTime" label="申请时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="reviewTime" label="审核时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatTime(row.reviewTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="rejectreason" label="驳回理由" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.rejectreason || row.rejectReason">{{ row.rejectreason || row.rejectReason }}</span>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button
              size="small"
              type="success"
              @click="approve(row)"
              :icon="Check"
              v-if="row.status === 0"
            >
              通过
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="reject(row)"
              :icon="Close"
              v-if="row.status === 0"
            >
              驳回
            </el-button>
            <span v-else style="color: #909399;">-</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty v-if="!loading && filteredList.length === 0" description="暂无申请记录" :image-size="150" />
    </el-card>

      <!-- 驳回理由弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="驳回申请" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef" label-width="100px">
        <el-form-item label="驳回理由" prop="reason">
          <el-input
            type="textarea"
            v-model="rejectForm.reason"
            placeholder="请输入驳回理由"
            :rows="4"
            maxlength="255"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="submitReject" :loading="rejecting" :icon="Close">
          确定驳回
        </el-button>
      </template>
    </el-dialog>

    <!-- 详情查看弹窗 -->
    <el-dialog 
      v-model="detailDialogVisible" 
      :title="detailTitle" 
      width="600px"
      :close-on-click-modal="true"
    >
      <div class="detail-content">
        <el-icon class="detail-icon"><DocumentChecked /></el-icon>
        <div class="detail-text">{{ detailContent || '暂无内容' }}</div>
      </div>
      <template #footer>
        <el-button type="primary" @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { DocumentChecked, Search, Refresh, Check, Close, View } from '@element-plus/icons-vue';

export default {
  name: "AdoptionReview",
  components: {
    DocumentChecked,
    Search,
    Refresh,
    Check,
    Close,
    View
  },
  data() {
    return {
      loading: false,
      records: [],
      searchKeyword: '',
      filterStatus: '',
      dialogVisible: false,
      rejecting: false,
      currentRecord: null,
      detailDialogVisible: false,
      detailTitle: '',
      detailContent: '',
      rejectForm: {
        reason: ''
      },
      rejectRules: {
        reason: [
          { required: true, message: '请输入驳回理由', trigger: 'blur' },
          { min: 5, message: '驳回理由至少5个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    filteredList() {
      let result = this.records;
      
      // 关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(item => 
          (item.applicantName || '').toLowerCase().includes(keyword) ||
          (item.phone || '').includes(keyword) ||
          (item.address || '').toLowerCase().includes(keyword)
        );
      }
      
      // 状态筛选
      if (this.filterStatus !== '') {
        result = result.filter(item => item.status === this.filterStatus);
      }
      
      return result;
    }
  },
  async mounted() {
    await this.loadData();
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        const res = await axios.get("http://localhost:8080/api/adoptionreview/listAll");
        if (res.data.code === 200) {
          this.records = res.data.data || [];
        } else {
          ElMessage.error(res.data.msg || '加载数据失败');
        }
      } catch (error) {
        console.error('加载数据失败:', error);
        ElMessage.error('加载数据失败：' + (error.response?.data?.msg || error.message));
      } finally {
        this.loading = false;
      }
    },
    
    async approve(row) {
      try {
        await ElMessageBox.confirm(
          `确定要通过用户"${row.applicantName || '未知'}"的领养申请吗？`,
          '审核确认',
          {
            confirmButtonText: '确定通过',
            cancelButtonText: '取消',
            type: 'success'
          }
        );
        
        await axios.put("http://localhost:8080/api/adoptionreview/review", {
          id: row.id,
          status: 1,
        });
        ElMessage.success("审核通过");
        await this.loadData();
      } catch (error) {
        if (error === 'cancel') return;
        console.error('审核失败:', error);
        ElMessage.error(error.response?.data?.msg || '审核失败');
      }
    },
    
    reject(row) {
      this.currentRecord = row;
      this.rejectForm.reason = '';
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.rejectFormRef) {
          this.$refs.rejectFormRef.clearValidate();
        }
      });
    },
    
    async submitReject() {
      if (!this.$refs.rejectFormRef) return;
      
      try {
        await this.$refs.rejectFormRef.validate();
        this.rejecting = true;
        
        await axios.put("http://localhost:8080/api/adoptionreview/review", {
          id: this.currentRecord.id,
          status: 2,
          rejectReason: this.rejectForm.reason,
        });
        
        ElMessage.success("已驳回");
        this.dialogVisible = false;
        this.rejectForm.reason = '';
        await this.loadData();
      } catch (error) {
        if (error.errors) {
          // 表单验证错误
          return;
        }
        console.error('驳回失败:', error);
        ElMessage.error(error.response?.data?.msg || '驳回失败');
      } finally {
        this.rejecting = false;
      }
    },
    
    handleSearch() {
      // 搜索逻辑已在computed中实现
    },
    
    handleReset() {
      this.searchKeyword = '';
      this.filterStatus = '';
    },
    
    formatTime(time) {
      if (!time) return '-';
      try {
        const date = new Date(time.replace(' ', 'T'));
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      } catch (error) {
        return time;
      }
    },
    
    getStatusText(status) {
      const statusMap = {
        0: '待审核',
        1: '已通过',
        2: '已驳回'
      };
      return statusMap[status] || '未知';
    },
    
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'success',
        2: 'danger'
      };
      return typeMap[status] || 'info';
    },
    
    showDetailDialog(title, content) {
      this.detailTitle = title;
      this.detailContent = content || '暂无内容';
      this.detailDialogVisible = true;
    }
  },
};
</script>

<style scoped>
.review-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.main-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 20px;
  color: #409eff;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

/* 表格样式 */
:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table__header th) {
  background: #fafafa;
  color: #303133;
  font-weight: 600;
}

:deep(.el-table__row:hover) {
  background: #f5f7fa;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  padding: 20px 20px 10px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 可点击文本样式 */
.clickable-text {
  color: #409eff;
  cursor: pointer;
  transition: color 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.clickable-text:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.view-icon {
  font-size: 14px;
  margin-left: 4px;
}

/* 可点击标签样式 */
.clickable-tag {
  cursor: pointer;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.clickable-tag:hover {
  opacity: 0.8;
  transform: scale(1.05);
}

/* 详情对话框样式 */
.detail-content {
  padding: 20px;
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.detail-icon {
  font-size: 24px;
  color: #409eff;
  flex-shrink: 0;
  margin-top: 2px;
}

.detail-text {
  flex: 1;
  font-size: 15px;
  line-height: 1.8;
  color: #303133;
  white-space: pre-wrap;
  word-break: break-word;
}

/* 响应式 */
@media (max-width: 768px) {
  .review-page {
    padding: 15px;
  }
  
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar .el-input,
  .search-bar .el-select {
    max-width: 100% !important;
    width: 100% !important;
  }
}
</style>